﻿$("#app").show();

const clientKey = 'f7hcLXDDkLiJoTiSUzg7rRHSqfuFbzEC';
const serverUrl = "https://api.vote.jdytp.com/";
var vxccn = localStorage.getItem('ccn')
if (!vxccn) {
    vxccn = md5((Math.random() * 10000000) + '')
    localStorage.setItem('ccn', vxccn)
}
var ua = navigator.userAgent;
const vxcid = md5(ua + vxccn + clientKey);
var token = localStorage.getItem('token');
// 适用富文本编辑器插件
Vue.use(VueHtml5Editor, {
    showModuleName: false,
    language: "zh-cn",
    image: {
        sizeLimit: 3 * 1024 * 1024,
        upload: {
            url: serverUrl + 'common/upload',
            headers: {
                'ccn': vxccn,
                'cid': vxcid,
                'token': token
            },
            fieldName: 'file'
        },
        compress: {
            width: 800,
            height: 800,
            quality: 80
        },
        uploadHandler(responseText) {
            var json = JSON.parse(responseText)
            if (json.code != 0) {
                Vant.Toast(json.msg)
            } else {
                return json.data
            }
        }
    }
});
// 图片的赖加载
Vue.use(vant.Lazyload);

var mySwiper;
var app = new Vue({
    el: '#app',
    data: {
        // 设置默认tababr,在主页
        tabBarItem: 'home',
        // tabbar展示
        tabBarItems: [
            {
                title: '首页',
                key: 'home',
                show: true,
                icon: 'wap-home-o'
            },
            {
                title: '介绍',
                key: 'intro',
                show: true,
                icon: 'notes-o'
            },
            {
                title: '排名',
                key: 'rank',
                show: true,
                icon: 'bar-chart-o'
            },
            {
                title: '搜索',
                key: 'search',
                show: true,
                icon: 'search'
            },
            {
                title: '报名',
                key: 'signup',
                show: false,
                icon: 'orders-o'
            },
            {
                title: '自定义',
                key: 'custom',
                show: false,
                icon: 'setting-o'
            }
        ],
        searchKey: '',
        openIntroText: '展开',
        showIntro: true,
        showSearch: true,
        startTime: '2022-01-01 12:00:00',
        endTime: '2022-12-01 12:00:00',
        pageIndex: 1,
        actId: '',
        curGroup: null,
        subGroup: null,
        thirdGroup: null,
        showSearchDlg: false,
        showPlayerInfo: false,
        countObj: {
            day: 0,
            hour: 0,
            minute: 0,
            second: 0
        },
        primaryColor: '',
        primaryBg: '',
        primaryBorder: '',
        covers: [],
        testMode: true,
        actData: {
            title: '活动标题',
            bgImage: '',
            bgMusic: '',
            drift: '',
            notice: '',
            showNotice: false,
            coverType: 1,
            showBottomAd: false,
            bottomAdImage: '',
            bottomAdUrl: '',
            bottomMenu: '',
            startTime: 0,
            endTime: 0,
            showOpenAd: false,
            openAdImage: '',
            playerCall: '选手',
            PlayerUnit: '个',
            voteStart: -1,
            voteEnd: -1,
            showAuth: false,
            showPopAd: false,
            popAdImage: '',
            popAdUrl: '',
            showPlayerInfo: true,
            canEnroll: false,
            primaryColor: '',
            canReply: false,
            openIntro: false,
            tempCode: '',
            showType: 0,
            covers: [],
            intro: '',
            btnText: '投票',
            tickUnit: '票',
            showGroup: false,
            groupCols: 3,
            groups: [{ name: '分组一' }, { name: '分组二' }],
            ruleText: '',
            tickets: 0,
            playerCount: 0,
            viewNum: 0,
            enroll: {
                playerNameTitle: '选手名称',
                playerPhone: 2,
                playerPhoneTitle: '选手电话',
                playerPhoto: 2,
                playerPhotoTitle: '选手照片',
                playerPhotoMin: 1,
                playerPhotoMax: 3,
                playerInfo: 2,
                playerInfoTitle: '选手简介',
                playerAudio: 1,
                playerAudioTitle: '选手音频',
                playerVideo: 2,
                playerVideoTitle: '选手视频',
                items: [],
                startTime: 0,
                endTime: 0
            },
            rule: {
                multi: false,
                playerMinLimit: 1,
                playerMaxLimit: 1,
            },
            showSupport: 1,
            support: '筋斗云投票 提供技术支持'
        },
        defSupport: '筋斗云投票 提供技术支持',
        groupFields: {
            text: 'name',
            value: 'id',
            children: 'subGroups'
        },
        enrollObj: {
            name: '',
            video: '',
            audio: '',
            info: '',
            phone: '',
            photo: '',
            group: 0,
            items: [],
            actId: ''
        },
        audioList: [],
        videoList: [],
        photoList: [],
        rankPlayers: [
            {
                id: 1,
                serial: 1,
                name: '一号选手',
                ticket: 999,
                cover: '../image/deface.png'
            }, {
                id: 2,
                serial: 2,
                name: '二号选手',
                ticket: 888,
                cover: '../image/deface.png'
            }, {
                id: 3,
                serial: 3,
                name: '三号选手',
                ticket: 777,
                cover: '../image/deface.png'
            }, {
                id: 4,
                serial: 4,
                name: '四号选手',
                ticket: 666,
                cover: '../image/deface.png'
            }
        ],
        players: [{
            id: 1,
            serial: 1,
            name: '一号选手',
            ticket: 999,
            cover: '../image/deface.png'
        }, {
            id: 2,
            serial: 2,
            name: '二号选手',
            ticket: 888,
            cover: '../image/deface.png'
        }, {
            id: 3,
            serial: 3,
            name: '三号选手',
            ticket: 777,
            cover: '../image/deface.png'
        }, {
            id: 4,
            serial: 4,
            name: '四号选手',
            ticket: 666,
            cover: '../image/deface.png'
        }],
        playerInfo: {
            id: 0,
            serial: 0,
            name: '',
            cdn: '',
            face: '',
            covers: [],
            audio: '',
            video: '',
            info: '',
            ticket: 0,
            ranking: 0,
            disparity: 0
        },
        replyContent: '',
        playerId: 0,
        replyList: [],
        replyPage: 1,
        replySize: 10,
        replyRecordCount: 0,
        showReplyDlg: false,
        ossToken: null,
        musicType: 2,
        videoType: 2,
        cdn: 'https://static.jdytp.com/',
        appId: '',
        audio: null,
        actOver: false,
        showPopDlg: false,
        popDlgTitle: '投票成功',
        popDlgMsg: '',
        openAdSec: 3,
        playerAudioPlay: null,
        playerVideoPlay: null,
        showAuthDlg: false,
        shareData: {
            image: '',
            title: '',
            content: ''
        },
        menuShareData: {
            image: '',
            title: '',
            content: ''
        },
        votePlayers: [],
        votePlayerId: 0,
        authUrl: '',
        voteAuthCode: '',
        jsapiConfig: {},
        showPosterDlg: false,
        musicState: false,
        selText: '选择',
        unselText: '已选择',
        showGroupLabel: '',
        showPopGroup: false,
        inited: false,
        rankGroup1: null,
        rankGroup2: null,
        rankGroup3: null,
        tempId: '',
        zipCode: '?imageMogr2/thumbnail/600x/format/webp/interlace/1/quality/65',
        filterShareIds: ['a1SOi5', 'X1CGOS']
    },
    computed: {
        // 展示所有分组,返回一个布尔值
        showAllGroup() {
            return this.actData.shareId && this.filterShareIds.indexOf(this.actData.shareId) == -1;
        }
    },
    mounted() {
        // 初始化轮播图
        this.initSwiper();
    },
    created() {
        if (!this.isWeixin()) {
            window.onmessage = this.onMessage;
        }
        var t = this.getQueryString('token');
        if (t) {
            token = t;
            localStorage.setItem('token', token);
        }

        this.getConfig();
        this.actId = this.getQueryString('act');
        if (this.actId) {
            this.testMode = false;
        } else {
            this.testMode = true;
        }
        this.enrollObj.actId = this.actId;
        this.audio = document.createElement('audio');
        this.audio.autoplay = true;
        this.audio.loop = true;
        document.body.appendChild(this.audio);
        this.audio.onplay = this.onAudioPlay;
        this.audio.onerror = this.onAudioError;
        this.initWx();
        this.accessLog();
        var player = this.getQueryString("player");
        if (player) {
            this.getPlayerInfo(player);
            setTimeout(this.getInfo, 200);
        } else {
            this.getInfo();
        }
        this.getShareData();
        // document.ontouchend = this.onTouchPage;
        document.ontouchstart = this.onTouchPage;
        document.onmousedown = this.onTouchPage;
    },
    methods: {
        onTouchPage() {
            if (this.musicState) return;
            if (this.actData.bgMusic && !this.musicState) {

                this.playMusic();
            }
        },
        onAudioPlay() {
            this.musicState = true;
            $("#musicCtl").removeClass("music_stop").addClass("music_play");
        },

        onAudioPlayInit() {
            if (this.actData.bgMusic) {
                $("#musicCtl").removeClass("music_stop").addClass("music_play");
            }            
        },


        autoPlayMusic() {
            // if (this.isWeixin()){                
            //     document.addEventListener("WeixinJSBridgeReady", function () { 
            //         onTouchPage();
            //     }, false);       
            // }
            // else {
            //     this.playMusic();                
            // }   

            if (this.isWeixin2()) {
                document.addEventListener("WeixinJSBridgeReady", function () {
                    this.playMusic();
                }, false);
            }
            else {
                this.playMusic();
            }
        },

        onAudioError() {
            this.musicState = false;
            this.pauseMusic();
        },
        checkTemp(s) {
            if (!s) return;
            var url = location.href;
            if (url.indexOf('localhost') > -1) return;
            var reg = /\/([a-zA-Z0-9]{6})\//i;
            var result = reg.exec(url);
            if (result[1] != s) {
                url = url.replace(result[0], '/' + s + '/');
                location.href = url;
            }
        },
        // 初始化轮播图
        initSwiper() {
            if (document.getElementById("swiper") == null)
                return;

            mySwiper = new Swiper("#swiper", {
                autoplay: {
                    delay: 3000,
                    disableOnInteraction: false
                },
                speed: 300,
                autoHeight: true,
                loop: true,
                loopedSlides: 5,
                observer: true,
                observeSlideChildren: true,
                observeParents: false,
                onSlideChangeEnd(swiper) {
                    swiper.update();
                    swiper.autoplay.start();
                    swiper.reLoop();
                }
            });
        },
        accessLog() {
            if (this.actId) {
                var json = localStorage.getItem('log');
                var alog = {};
                if (json) {
                    alog = JSON.parse(json);
                }
                alog[this.actId] = this.getTimestamp();
                json = JSON.stringify(alog);
                localStorage.setItem('log', json);
            }
        },
        getLastTime() {
            if (this.actId) {
                var json = localStorage.getItem('log');
                var alog = {};
                if (json) {
                    alog = JSON.parse(json);
                }
                if (alog[this.actId])
                    return alog[this.actId];
            }
            return "0";
        },
        initWx() {
            //初始化微信相关接口
            if (this.isWeixin()) {
                var u = location.href;
                var n = u.indexOf("#");
                if (n > 0) {
                    u = u.substring(0, n);
                }
                const that = this;
                this.request({
                    url: 'common/jsapi/sign?url=' + encodeURIComponent(u),
                    method: 'get',
                    success(res) {
                        if (res.code == 0) {
                            that.jsapiConfig = res.data;
                            that.initWxConfig();
                        } else {
                            console.log(res);
                        }
                    }, error(a, b) {
                        console.error(a, b);
                    }
                })
            }
        },
        // 初始化微信分享
        initWxShareData() {
            var url = location.href;
            var n = url.indexOf("?");
            if (n > 0) {
                var pre = url.substr(0, n);
                var sub = url.substr(n + 1);
                var ary = sub.split('&'), ps = [];
                for (var i in ary) {
                    var tt = ary[i].indexOf('=');
                    if (tt > 0) {
                        var name = ary[i].substr(0, tt);
                        if (name == 'token' || name == 'player') continue;
                        var val = ary[i].substr(tt + 1);
                        ps.push(name + "=" + val);
                    }
                }
                if (this.showPlayerInfo) {
                    ps.push('player=' + this.playerId);
                }
                url = pre + '?' + ps.join('&');
            }
            var image = this.menuShareData.image;
            if (this.zipCode) image += this.zipCode;

            wx.onMenuShareAppMessage({
                title: this.menuShareData.title,
                desc: this.menuShareData.content,
                link: url,
                imgUrl: image,
                success() {
                    console.log('wx menu share ok');
                }, cancel() {
                }
            });
            wx.updateAppMessageShareData({
                title: this.menuShareData.title,
                desc: this.menuShareData.content,
                link: url,
                imgUrl: image,
                success() {
                    console.log('wx share to friend ok');
                }, cancel() {
                }
            });
            wx.onMenuShareTimeline({
                title: this.menuShareData.title,
                link: url,
                imgUrl: image,
                success() {
                    console.log('wx share to time line ok');
                }, cancel() {
                }
            });
        },
        initWxConfig() {
            wx.config({
                debug: false,
                appId: this.jsapiConfig.appId,
                timestamp: this.jsapiConfig.timestamp,
                nonceStr: this.jsapiConfig.nonce,
                signature: this.jsapiConfig.sign,
                jsApiList: ["chooseImage", "getLocalImgData", "onMenuShareQZone", "onMenuShareQQ", "onMenuShareAppMessage", "onMenuShareTimeline", "updateTimelineShareData", "updateAppMessageShareData"]
            });
            const that = this;
            wx.ready(function () {
                that.initWxShareData();
            });
        },
        getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substring(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]); return null;
        },
        onMessage(msg) {
            if (msg) {
                this.actData = msg.data;
                this.initPage();
            }
        },
        // 改变音乐的状态
        changeMusicState() {
            if (this.musicState && !this.audio.paused) {
                this.pauseMusic();
            } else {
                this.playMusic();
            }
        },
        pauseMusic() {
            this.audio.pause();
            $("#musicCtl").removeClass("music_play").addClass("music_stop");
        },
        // 播放音乐
        playMusic() {
            if (this.actData.bgMusic) {
                $("#musicCtl").show();
                this.audio.pause();
                this.audio.preload = "auto";
                this.audio.src = this.cdn + this.actData.bgMusic;
                this.audio.load();
                try {
                    this.audio.play();
                } catch (err) {
                    this.pauseMusic();
                }
            } else {
                this.pauseMusic();
                $("#musicCtl").hide();
                setTimeout(function () {
                    $("#musicCtl").hide();
                }, 200);
            }
        },
        // 微信分享
        shareToFriend() {
            const that = this;
            wx.ready(function () {
                var url = that.shareData.url;
                if (!url) url = location.href;
                wx.updateAppMessageShareData({
                    title: that.shareData.title,
                    desc: that.shareData.content,
                    link: url,
                    imgUrl: that.shareData.image,
                    success() {
                        //分享成功
                    }, cancel() {
                    }
                });

                that.showPosterDlg = false;
            });
        },
        shareToWx() {
            const that = this;
            wx.ready(function () {
                var url = that.shareData.url;
                if (!url) url = location.href;
                wx.onMenuShareTimeline({
                    title: that.shareData.title,
                    link: url,
                    imgUrl: that.shareData.image,
                    success() {
                        //分享成功
                    }, cancel() {

                    }
                });

                that.showPosterDlg = false;
            });
        },
        isWeixin() {
            return navigator.userAgent.match(/MicroMessenger/i);
        },

        isWeixin2() {
            var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
            if (ua.match(/MicroMessenger/i) == "micromessenger") {
                return true;
            }
            else {
                return false;
            }
        },

        // 微信配置
        getConfig() {
            const that = this;
            this.request({
                url: 'common/mpconfig',
                method: 'get',
                success(res) {
                    if (res.code == 0) {
                        that.appId = res.data.appId;
                        that.cdn = res.data.cdn;
                        if (!res.data.login) {
                            that.wxOauth2();
                        }
                    } else {
                        vant.Toast('获取配置失败');
                    }
                }, error(a, b) {

                }
            })
        },
        wxOauth2() {
            if (this.isWeixin()) {
                var retUrl = encodeURIComponent(location.href);
                var loginUrl = encodeURIComponent(serverUrl + 'user/oauth/login?url=' + retUrl);
                var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
                    this.appId + '&redirect_uri=' + loginUrl + '&response_type=code&scope=snsapi_userinfo&state=' +
                    vxcid + '#wechat_redirect';
                location.href = url;
            }
        },
        // 封装请求
        request(config) {
            var headers = {
                'cid': vxcid,
                'ccn': vxccn,
                'token': encodeURIComponent(token),
                'Content-Type': 'application/json;charset=utf8'
            };
            if (config.headers) {
                for (var n in config.headers) {
                    headers[n] = config.headers[n];
                }
            }

            $.ajax({
                url: serverUrl + config.url,
                headers: headers,
                dateType: 'JSON',
                type: config.method,
                xhrFields: { withCredentials: true },
                data: JSON.stringify(config.data),
                success(res) {
                    if (config.success) {
                        config.success(res);
                    }
                }, error(a, b) {
                    if (config.error) {
                        config.error(a, b);
                    }
                }
            })
        },
        // 获取活动信息
        getInfo() {
            if (this.actId) {
                const that = this;
                this.request({
                    url: 'activity/info/' + this.actId,
                    method: 'get',
                    headers: {
                        'last-time': this.getLastTime()
                    },
                    success(res) {
                        if (res.code == 0) {
                            that.actData = res.data;
                            that.checkTemp(res.data.tempCode);
                            that.sortGroups(that.actData.groups);
                            that.selectDefaultGroup();
                        }
                        $(".multi_vote").hide();
                        that.initPage();
                    }, error(a, b) {
                        vant.Toast('数据加载失败');
                    }
                });

                /*setTimeout(function () {
                    that.loadGroupPlayer(null);
                }, 10);*/

            } else {
                this.initPage();
            }
        },
        // 分组排序
        sortGroups(groups) {
            if (groups) {
                groups.sort((a, b) => {
                    //return b.sort - a.sort;
                    return a.sort - b.sort;
                });
                const that = this;
                groups.forEach((v, i, ary) => {
                    if (v.subGroups) that.sortGroups(v.subGroups);
                });
            }
        },
        // 初始化页面
        initPage() {
            if (this.inited) {
                $(".fullAd").hide();
                this.actData.showOpenAd = false;
            }
            if (this.actData.state < 1) {
                location.href = "https://wx.jdytp.com/closed.html";
                return;
            }

            this.inited = true;
            if (this.actData.title) {
                try {
                    document.title = this.actData.title;
                } catch (err) {
                    console.error(err);
                }
            }
            this.refreshAuth();
            this.playMusic();
            this.onAudioPlayInit();
            this.autoPlayMusic();

            this.openAdSec = 3;

            if (this.actData.startTime < 1) {
                this.actData.startTime = this.getTimestamp();
            }
            if (this.actData.endTime < 1) {
                this.actData.endTime = this.getTimestamp() + 15 * 24 * 3600;
            }
            if (this.actData.voteStart < 0) {
                this.actData.voteStart = 50000;
            }
            if (this.actData.voteEnd < 0) {
                this.actData.voteEnd = 235959;
            }

            this.actOver = this.actData.endTime <= this.getTimestamp();

            if (this.actId && this.actOver && !this.testMode) {
                vant.Dialog.alert({ message: '活动已结束' });
            }
            if (this.isEmpty(this.actData.support)) {
                this.actData.support = this.defSupport;
            }

            this.startTime = this.fromTimestamp(this.actData.startTime);
            this.endTime = this.fromTimestamp(this.actData.endTime);

            if (this.actData.bottomMenu) {
                var menu = JSON.parse(this.actData.bottomMenu);
                var n = 0;
                for (var i in this.tabBarItems) {
                    this.tabBarItems[i].show = false;
                }
                for (var i in menu) {
                    var m = menu[i];
                    for (var j in this.tabBarItems) {
                        var item = this.tabBarItems[j];
                        if (item.key == m.key) {
                            if (n >= 5) {
                                item.show = false;
                            } else {
                                item.show = true;
                            }
                            if (item.key == 'custom') {
                                item.title = m.name;
                                if (m.url) item.url = m.url;
                            }
                            if (item.show) n++;
                            break;
                        }
                    }
                }
            }
            if (this.actData.primaryColor && !isNaN(this.actData.primaryColor)) {
                this.primaryBg = 'cus_bg_' + this.actData.primaryColor;
                this.primaryColor = 'cus_color_' + this.actData.primaryColor;
                this.primaryBorder = 'cus_bd_' + this.actData.primaryColor;
            }
            this.actData.popAdImage = this.fillUrl(this.actData.popAdImage);
            this.actData.openAdImage = this.fillUrl(this.actData.openAdImage);

            if (!this.actData.popAdImage) {
                this.actData.showPopAd = false;
            }

            if (!this.actData.openAdImage) {
                this.actData.showOpenAd = false;
            }
            if (this.actData.showOpenAd) {
                setTimeout(this.delayCloseOpenAd, 1000, this);
            }

            if (this.actData.endTime > this.getTimestamp()) {
                this.countDown();
            }

            if (this.showPlayerInfo && this.playerInfo.covers && this.playerInfo.covers.length > 0) {
                this.initCovers(this.playerInfo.covers);
            } else {
                this.initCovers(this.actData.covers);
            }

            this.openIntroText = this.actData.openIntro ? '折叠' : '展开';

            if (this.actData.drift) {
                if (typeof (floater) == 'function') {
                    floater(10, this.cdn + this.actData.drift);
                } else {
                    const that = this;
                    $.getScript('/js/floater.js', function () {
                        floater(10, that.cdn + that.actData.drift);
                    });
                }
            } else {
                if (typeof (clearFloater) == 'function') {
                    clearFloater();
                } else {
                    $.getScript('/js/floater.js', function () {
                        clearFloater();
                    });
                }
            }


            if (this.actData.showOpenAd && this.actData.openAdImage) {
                $(".fullAd").show();
                setTimeout(function () {
                    $(".fullAd").show();
                }, 200);
            }

            if (this.actData.bgImage) {
                var img = this.cdn + this.actData.bgImage + this.zipCode;
                if ($(".bg-img").size() == 0) {
                    $("#app").append("<div class='bg-img'></div>");
                }
                $(".bg-img").css('background-image', 'url(' + img + ')');
                $(".app-wrapper").css('cssText', 'background-color:unset!important;background-image:unset!important');
            } else {
                $(".bg-img").css('background-image', '');
                $(".app-wrapper").css('background-color', '');
                $(".app-wrapper").css('background-image', '');
            }

            if (this.votePlayers && this.votePlayers.length > 0) {
                $(".multi_vote").show();
            } else {
                $(".multi_vote").hide();
            }



            this.$forceUpdate();


        },
        getBtnText(id) {
            if (this.actData.multi) {
                return this.votePlayers.includes(id) ? '已选择' : '选择';
            } else {
                return this.actData.btnText;
            }
        },
        formatTime(t) {
            var h = parseInt(t / 10000), m = parseInt(t % 10000 / 100), s = parseInt(t % 100);
            return this.fill0(h) + ':' + this.fill0(m) + ':' + this.fill0(s);
        },
        delayCloseOpenAd(that) {
            that.openAdSec--;
            if (that.openAdSec <= 0) {
                that.actData.showOpenAd = false;
                return;
            }
            setTimeout(that.delayCloseOpenAd, 1000, that);
        },
        fillUrl(url) {
            if (url) {
                if (!(url.indexOf('http:') == 0 || url.indexOf('https:') == 0)) {
                    url = this.cdn + url;
                }
            }
            return url;
        },
        refreshPoster() {
            //刷新海报
            if (this.shareData) {
                this.delaySet('shareImg', 'src', this.shareData.image);
            }
        },
        // 微信分享链接
        getShareData() {
            if (this.actId) {
                var pid = this.playerId;
                if (!this.showPlayerInfo) pid = 0;
                const that = this;
                this.request({
                    url: 'activity/share/' + this.actId + '?player=' + pid,
                    method: 'get',
                    success(res) {
                        if (res.code == 0) {
                            that.menuShareData = res.data;
                            that.initWxShareData();
                        } else {
                            console.error(res);
                        }
                    }
                })
            }
        },
        makePoster(ss) {
            if (this.actId) {
                //生成海报
                var pid = this.playerId;
                if (!this.showPlayerInfo) pid = 0;

                const that = this;
                this.request({
                    url: 'activity/poster/' + this.actId + '?player=' + pid,
                    method: 'get',
                    success(res) {
                        if (res.code == 0) {
                            that.shareData = res.data;
                            that.shareData.image += "?v=" + Math.random();
                            if (ss) {
                                that.showPosterDlg = true;
                                that.refreshPoster();
                            }
                        } else {
                            that.alert('海报生成失败：' + res.msg);
                        }
                    }, error(a, b) {
                        that.alert('海报生成失败');
                    }
                })
            }
        },
        // 初始化图片
        initCovers(list) {
            if (document.getElementById("swiper") == null)
                return;

            $("#swiper .swiper-slide").remove();
            this.covers = [];
            var imgs = [];
            if (list && list.length > 0) {
                for (var i in list) {
                    var c = this.fillUrl(list[i]);
                    imgs.push(c);
                }
            } else {
                imgs.push('../image/def.png');
            }

            for (var i in imgs) {
                var c = this.zipCode ? imgs[i] + this.zipCode : imgs[i];
                var sub = '<div class="swiper-slide"><img src="' + c + '" /></div>';

                if (mySwiper && mySwiper.appendSlide) {
                    mySwiper.appendSlide(sub);
                } else {
                    if ($("#swiper .swiper-wrapper").size() == 0) {
                        setTimeout(function (ss) {
                            $("#swiper .swiper-wrapper").append(ss);
                        }, 100, sub);
                    } else {
                        $("#swiper .swiper-wrapper").append(sub);
                    }
                }
            }
            if (imgs.length == 1) {
                if (mySwiper) {
                    mySwiper.activeIndex = 0;
                    mySwiper.autoplay.stop();
                }
            } else {
                if (mySwiper) {
                    mySwiper.activeIndex = 0;
                    mySwiper.autoplay.start();
                }
            }
            this.refreshSwiper();
        },
        // 刷新轮播图
        refreshSwiper() {
            if (document.getElementById("swiper") == null)
                return;

            if (mySwiper) {
                mySwiper.update();
                var c = mySwiper.slides[mySwiper.activeIndex];
                $(c).find("img").on('load', function () {
                    mySwiper.update();
                });
            } else {
                setTimeout(this.refreshSwiper, 10);
            }
        },
        fill0(n) {
            return n > 9 ? n : '0' + n;
        },
        getTimestamp() {
            return parseInt((new Date()).getTime() / 1000);
        },
        // 处理时间
        fromTimestamp(ts) {
            var date = new Date(ts * 1000);
            var y = date.getFullYear(),
                m = date.getMonth() + 1,
                d = date.getDate(),
                h = date.getHours(),
                mm = date.getMinutes(),
                s = date.getSeconds();
            return y + '-' + this.fill0(m) + '-' + this.fill0(d) + ' ' + this.fill0(h) + ':' + this.fill0(mm) + ':' + this.fill0(s);
        },
        clearPlayerInfo() {
            this.showPlayerInfo = false;
            if (this.actData.title) {
                document.title = this.actData.title;
            } else {
                document.title = '筋斗云投票';
            }
            this.playerId = 0;
            if (this.playerAudioPlay) {
                this.playerAudioPlay.pause();
            }
            if (this.playerVideoPlay) {
                this.playerVideoPlay.pause();
            }
            if (this.actData.rule.multi) {
                $(".multi_vote").show();
            }
            this.initCovers(this.actData.covers);
        },
        // 跳转到上一个tabbar
        onNavBack() {
            this.onTabbarChange(this.tabBarItem);
        },
        onTabbarChange(e) {
            this.clearPlayerInfo();
            var hasChange = this.tabBarItem != e;
            this.tabBarItem = e;
            switch (e) {
                case 'home':
                    this.showIntro = true;
                    this.showSearch = true;
                    this.pageIndex = 1;
                    if (hasChange && this.searchKey) {
                        this.searchKey = "";
                        this.onSearch();
                    }
                    break;
                case 'intro':
                    //活动介绍
                    this.showIntro = false;
                    this.showSearch = false;
                    this.pageIndex = 2;
                    break;
                case 'rank':
                    //排行榜
                    this.showIntro = false;
                    this.showSearch = false;
                    this.pageIndex = 3;
                    break;
                case 'search':
                    //弹出搜索对话框
                    this.showSearchDlg = true;
                    this.tabBarItem = 'home';
                    this.onTabbarChange('home');
                    break;
                case 'signup':
                    //在线报名
                    this.showIntro = false;
                    this.showSearch = false;
                    this.pageIndex = 4;
                    break;
                case 'custom':
                    var ary = this.tabBarItems.filter(x => x.key == e);
                    if (ary && ary.length > 0) {
                        if (ary[0].url) {
                            location.href = ary[0].url;
                        }
                    }
                    break;
            }
            this.getShareData();
            if (this.actData.rule.multi && this.votePlayers && this.votePlayers.length > 0) {
                $(".multi_vote").show();
                $("#app").css('padding-bottom', '80px');
            } else {
                $(".multi_vote").hide();
                $("#app").css('padding-bottom', '');
            }
        },
        countDown() {
            var now = (new Date()).getTime() / 1000;
            var sub = this.actData.endTime - now;
            if (sub <= 0) {
                this.countObj.day = 0;
                this.countObj.hour = 0;
                this.countObj.minute = 0;
                this.countObj.second = 0;
                return;
            }
            this.countObj.day = parseInt(sub / (24 * 3600));
            sub = sub % (24 * 3600);
            this.countObj.hour = parseInt(sub / 3600);
            sub = sub % 3600;
            this.countObj.minute = parseInt(sub / 60);
            this.countObj.second = parseInt(sub % 60);
            setTimeout(function (that) {
                that.countDown();
            }, 1000, this);
        },
        // 活动介绍折叠或者展开
        doOpenIntro() {
            this.actData.openIntro = !this.actData.openIntro;
            this.openIntroText = this.openIntro ? '折叠' : '展开';
        },
        isEmpty(s) {
            return s == undefined || !s || s == '' || s.trim() == '';
        },
        alert(m) {
            if (m) {
                vant.Dialog.alert({ message: m });
            }
        },
        isMobile(s) {
            if (!s) return false;
            var reg = /^1[3|4|5|6|7|8|9]\d{9}$/ig;
            return reg.test(s);
        },
        onSignup() {
            //报名
            if (this.isEmpty(this.enrollObj.name)) {
                this.alert(this.actData.enroll.playerNameTitle + '不能为空');
                return;
            }

            if (this.actData.enroll.playerPhoto == 1) {
                if (!this.enrollObj.photo) {
                    this.alert('请上传' + this.actData.enroll.playerPhotoTitle);
                    return;
                }
                var ary = JSON.parse(this.enrollObj.photo);
                if (ary.length == 0) {
                    this.alert('请上传' + this.actData.enroll.playerPhotoTitle);
                    return;
                }
            }

            if (this.actData.enroll.playerPhone == 1) {
                //必填
                if (!this.isMobile(this.enrollObj.phone)) {
                    this.alert('请输入正确的手机号码');
                    return;
                }
            }

            if (this.actData.groups && this.actData.groups.length > 0
                && this.enrollObj.group < 1) {
                this.alert('请选择分组');
                return;
            }

            if (this.actData.enroll.playerInfo == 1) {
                if (this.isEmpty(this.enrollObj.info)) {
                    this.alert('请填写' + this.actData.enroll.playerInfoTitle);
                    return;
                }
            }
            if (this.actData.enroll.playerAudio == 1) {
                if (this.isEmpty(this.enrollObj.audio)) {
                    this.alert('请上传' + this.actData.enroll.playerAudioTitle);
                    return;
                }
            }
            if (this.actData.enroll.playerVideo == 1) {
                if (this.isEmpty(this.enrollObj.video)) {
                    this.alert('请上传' + this.actData.enroll.playerVideoTitle);
                    return;
                }
            }
            if (this.actData.enroll.items) {
                this.enrollObj.items = [];
                for (var i in this.actData.enroll.items) {
                    var t = this.actData.enroll.items[i];
                    if (t.type == 1 && this.isEmpty(t.value)) {
                        this.alert(t.name + '不能为空');
                        return;
                    }
                    this.enrollObj.items.push(t);
                }
            }
            const that = this;
            this.request({
                url: 'user/enroll',
                data: this.enrollObj,
                method: 'post',
                success(res) {
                    if (res.code == 0) {
                        if (res.data) {
                            that.alert('报名成功，待活动创建者审核，即可显示！');
                        } else {
                            that.alert('报名成功！');
                            that.loadGroupPlayer(null);
                        }
                        that.onTabbarChange('home');
                    } else {
                        that.alert('报名失败: ' + res.msg);
                    }
                }, error(a, b) {
                    console.error(a, b);
                    that.alert('报名失败，网络错误');
                }
            })
        },
        onSearch() {
            this.showSearchDlg = false;
            this.loadGroupPlayer(this.curGroup, this.subGroup, this.thirdGroup);
        },
        refreshAuth() {
            this.authUrl = serverUrl + '/common/captcha?v=' + Math.random();
            this.delaySet('authimg', 'src', this.authUrl);
        },
        delaySet(id, attr, val) {
            var obj = document.getElementById(id);
            if (obj) {
                obj.setAttribute(attr, val);
            } else {
                setTimeout(function (that) {
                    that.delaySet(id, attr, val);
                }, 100, this);
            }
        },
        confirmAuth() {
            if (this.isEmpty(this.voteAuthCode)) {
                this.alert('请填写图形验证码');
                return false;
            }
            if (this.actData.rule.multi) {
                this.multiVote(true);
            } else {
                this.vote(this.votePlayerId, true);
            }
        },
        refreshPopAd() {
            if (this.actData.showPopAd) {
                this.delaySet('popImg', 'src', this.actData.popAdImage);
                this.delaySet('popLink', 'href', this.actData.popAdUrl);
            }
        },
        multiVote(c) {
            if (this.votePlayers.length < this.actData.rule.playerMinLimit) {
                this.alert('至少需要选择' + this.actData.rule.playerMinLimit + '个选手进行投票');
                return;
            }
            if (this.votePlayers.length > this.actData.rule.playerMaxLimit) {
                this.alert('最多只能选择' + this.actData.rule.playerMaxLimit + '个选手进行投票');
                return;
            }
            if (c) {
                if (typeof (c) == 'object') c = false;
            }
            if (!c && this.actData.showAuth) {
                this.voteAuthCode = '';
                this.showAuthDlg = true;
                this.refreshAuth();
                return;
            }

            var voteData = { actId: this.actId, player: this.votePlayers };
            if (this.actData.showAuth) {
                voteData.code = this.voteAuthCode;
            }
            this.doVote(voteData);
        },
        vote(id, c) {
            if (!id) id = this.votePlayerId;

            if (!this.actId || !id) return;
            if (this.actOver) {
                vant.Dialog.alert({ message: '活动已结束' });
                return;
            }

            this.votePlayerId = parseInt(id);

            if (!this.actData.rule.multi && !c && this.actData.showAuth) {
                this.voteAuthCode = '';
                this.showAuthDlg = true;
                this.refreshAuth();
                return;
            }

            if (this.actData.rule.multi) {
                var ary = this.players.filter(x => x.id == id),
                    item;
                if (ary != null && ary.length > 0) {
                    item = ary[0];
                }

                if (this.votePlayers.includes(id)) {
                    this.votePlayers = this.votePlayers.filter(x => x != id);
                    if (item) item.select = false;
                    if (this.showPlayerInfo) this.playerInfo.select = false;
                } else {
                    if (this.votePlayers.length >= this.actData.rule.playerMaxLimit) {
                        this.alert('最多只能选择' + this.actData.rule.playerMaxLimit + '个选手');
                        return;
                    }
                    if (this.showPlayerInfo) this.playerInfo.select = true;
                    if (item) item.select = true;
                    this.votePlayers.push(this.votePlayerId);
                }
                if (this.votePlayers.length > 0) {
                    $(".multi_vote").show();
                    $("#app").css('padding-bottom', '80px');
                } else {
                    $(".multi_vote").hide();
                    $("#app").css('padding-bottom', '');
                }
            } else {
                this.votePlayers = [this.votePlayerId];
                var voteData = { actId: this.actId, player: this.votePlayers };
                if (this.actData.showAuth) {
                    voteData.code = this.voteAuthCode;
                }
                this.doVote(voteData);
            }
        },
        doVote(data) {
            const that = this;
            let btnText = that.actData.btnText;

            this.request({
                url: 'user/vote',
                method: 'post',
                data: data,
                success(res) {
                    if (res.code == 0) {
                        //弹出投票成功对话框
                        that.popDlgMsg = btnText + '成功';
                        that.popDlgTitle = '';
                        that.showPopDlg = true;
                        that.votePlayers = [];
                        that.votePlayerId = 0;
                        //设置弹出广告
                        that.refreshPopAd();
                        //重新加载数据
                        that.getInfo();
                    } else if (res.code == 405) {
                        //需要输入验证码
                        that.actData.showAuth = true;
                        if (that.actData.rule.multi) {
                            that.multiVote();
                        } else {
                            that.vote(that.votePlayers[0]);
                        }
                    } else {
                        that.popDlgMsg = btnText + '失败：' + res.msg;
                        that.popDlgTitle = '';
                        that.showPopDlg = true;
                        that.refreshPopAd();
                    }
                }, error(a, b) {
                    console.error(a, b);
                    vant.Dialog.alert({ message: '网络错误，' + btnText + '失败' });
                }
            })
        },
        getPlayerInfo(id) {
            if (!this.actId || !this.actData.showPlayerInfo) return;
            const that = this;
            if (this.playerAudioPlay) {
                this.playerAudioPlay.src = '';
            }
            if (this.playerVideoPlay) {
                this.playerVideoPlay.src = '';
            }
            this.playerId = id;
            this.request({
                url: 'activity/player/info/' + this.actId + '/' + id,
                method: 'Get',
                success(res) {
                    if (res.code == 0) {
                        that.tabBarItem = 'playerinfo';

                        if (that.actData.rule.multi && that.votePlayers && that.votePlayers.length > 0) {
                            $(".multi_vote").show();
                        } else {
                            $(".multi_vote").hide();
                        }

                        $("#app").css('padding-bottom', '');
                        that.playerInfo = res.data;
                        //副标题单独处理
                        if (that.playerInfo.items) {
                            that.playerInfo.subTitle = '';
                            that.playerInfo.items.forEach((val, idx, ary) => {
                                if (val.name == 'subtitle') {
                                    that.playerInfo.subTitle = val.value;
                                }
                            });
                            that.playerInfo.items = that.playerInfo.items.filter(x => x.name != 'subtitle');
                        }

                        var arr = that.votePlayers.filter(x => x == id);
                        that.playerInfo.select = arr && arr.length > 0;
                        document.title = `${that.playerInfo.name} - ${that.actData.playerCall}详情`;
                        that.showPlayerInfo = true;
                        that.showSearch = false;
                        that.initMedia();
                        if (res.data.covers && res.data.covers.length > 0) {
                            that.initCovers(res.data.covers);
                            that.playerInfo.face = that.cdn + res.data.covers[0];
                        } else {
                            that.initCovers(that.actData.covers);
                            that.playerInfo.face = '../image/deface.png';
                        }
                        that.getShareData();

                        that.$nextTick(function () {
                            window.scrollTo(0, 0);
                        });
                    } else {
                        vant.Dialog.alert({ message: `获取${that.actData.playerCall}详情失败：${res.msg}` });
                    }
                }, error(a, b) {
                    console.error(a, b);
                }
            })
            this.loadPlayerReply();
        },
        // 提交评论
        submitReply() {
            if (this.replyContent == '') {
                vant.Dialog.alert({ message: '评论内容不能为空' });
                return;
            }
            const that = this;
            this.request({
                url: 'user/reply',
                method: 'post',
                data: { actId: this.actId, player: this.playerId, content: this.replyContent },
                success(res) {
                    if (res.code == 0) {
                        vant.Dialog.alert({ message: '评论发表成功，待活动创建者审核，即可显示' });
                    } else {
                        vant.Dialog.alert({ message: '评论发表失败：' + res.msg });
                    }
                    that.showReplyDlg = false;
                }, error(a, b) {
                    vant.Dialog.alert({ message: '评论发表失败：网络错误' });
                    that.showReplyDlg = false;
                }
            });
        },
        addReply() {
            this.replyContent = '';
            this.showReplyDlg = true;
        },
        loadPlayerReply() {
            const that = this;
            this.request({
                url: 'activity/player/reply/' + this.actId + '/' + this.playerId + '?page=' + this.replyPage + '&size=' + this.replySize,
                method: 'get',
                success(res) {
                    if (res.code == 0) {
                        that.replyRecordCount = res.data.recordCount;
                        that.replyList = res.data.data;
                    }
                },
                error(a, b) {
                    console.error(a, b);
                    that.replyList = [];
                }
            });
        },
        changeReplyPage() {
            this.loadPlayerReply();
        },
        endWith(s, e) {
            if (!s || !e) return false;
            var n = e.length, idx = s.indexOf(e);
            return idx >= 0 && s.length == (idx + n);
        },
        initAudio() {
            if (this.playerInfo.audio == null) this.playerInfo.audio = "";
            this.playerInfo.audio = this.fillUrl(this.playerInfo.audio);
            this.playerAudioPlay = document.getElementById('playerAudioPlay');

            if (this.playerInfo.audio != '' && this.playerAudioPlay) {
                this.playerAudioPlay.src = this.playerInfo.audio;
            }
            if (this.playerAudioPlay == null && this.playerInfo.audio != '') {
                setTimeout(function (that) {
                    that.playerAudioPlay = document.getElementById('playerAudioPlay');
                    if (that.playerAudioPlay != null) {
                        that.playerAudioPlay.src = that.playerInfo.audio;
                    } else {
                        that.initAudio();
                    }
                }, 500, this);
            }
        },
        initVideo() {
            console.log('init player video');
            if (this.playerInfo.video == null) this.playerInfo.video = '';
            this.playerInfo.video = this.fillUrl(this.playerInfo.video);
            this.playerVideoPlay = document.getElementById('playerVideoPlay');
            var isMp4 = this.endWith(this.playerInfo.video, ".mp4");
            if (this.playerInfo.video != '') {
                if (isMp4) {
                    $("#playerVideoPlay").show();
                    if (this.playerVideoPlay) {
                        this.playerVideoPlay.src = this.playerInfo.video;
                    } else {
                        setTimeout(function (that) {
                            $("#playerVideoPlay").show();
                            that.playerVideoPlay = document.getElementById('playerVideoPlay');
                            if (that.playerVideoPlay != null) {
                                that.playerVideoPlay.src = that.playerInfo.video;
                            } else {
                                that.initVideo();
                            }
                        }, 500, this);
                    }
                } else {
                    $("#playerVideoPlay").hide();
                    var pobj = $("#playerVideoPlay").parent();
                    if (pobj.length > 0) {
                        pobj.find("iframe").remove();
                        var iframe = "<iframe src='" + this.playerInfo.video + "' allowfullscreen='true' frameborder='0' class='videoframe' marginheight='0' marginwidth='0' scrolling='no'></iframe>";
                        pobj.append(iframe);
                    } else {
                        setTimeout(this.initVideo, 200);
                    }
                }
            }
        },
        initMedia() {
            if (document.getElementById("swiper") == null)
                return;
            this.initAudio();
            this.initVideo();
        },
        clone(obj) {
            var buf;
            if (obj instanceof Array) {
                buf = [];
                var l = obj.length;
                for (var i = 0; i < l; i++) {
                    buf[i] = this.clone(obj[i]);
                }
                return buf;
            }
            if (obj instanceof Object) {
                buf = {}
                for (var k in obj) {
                    buf[k] = this.clone(obj[k]);
                }
                return buf;
            }

            return obj;
        },
        loadGroupPlayer(g, s, t, p) {
            this.curGroup = g;
            this.subGroup = s;
            this.thirdGroup = t;
            var gid = 0;
            if (t) {
                gid = t.id;
            } else if (s) {
                gid = s.id;
            } else if (g) {
                gid = g.id;
            }

            if (!this.actId) return;
            const that = this;
            const pageSize = 100;
            var listPage = 1;
            if (p) {
                listPage = parseInt(p);
            }

            if (listPage == 1) {
                this.players = [];
            }
            //加载选手
            this.request({
                url: 'activity/players/' + this.actId + '?state=2&page=' + listPage + '&size=' + pageSize + '&group=' + gid + '&kw=' + encodeURIComponent(this.searchKey),
                method: 'get',
                success: function (res) {
                    if (res.code == 0) {
                        var players = res.data.data;
                        players.forEach((val, idx, ary) => {
                            val.select = false;
                            if (val.cover) {
                                val.cover += that.zipCode;
                            }
                            if (that.showPlayerInfo && that.playerInfo.id == val.id) {
                                that.playerInfo.ticket = val.ticket;
                            }
                            that.players.push(val);
                        });
                        if (gid == 0 && !this.searchKey) {
                            that.rankGroup2 = null;
                            that.rankGroup3 = null;
                            if (that.showAllGroup || that.actData.groups.length == 0) {
                                that.rankGroup1 = null;
                                that.setRankPlayers(0);
                            } else {
                                that.rankGroup1 = that.actData.groups[0];
                                that.setRankPlayers(that.rankGroup1.id);
                            }
                        }
                        if (listPage < res.data.pageCount) {
                            that.loadGroupPlayer(that.curGroup, that.subGroup, that.thirdGroup, listPage + 1);
                        }
                    }
                },
                error: function (a, b) {
                    vant.Dialog.alert({ message: '获取选手数据失败' });
                }
            })
        },
        findGroupAndSub(groups, gid, arr = []) {
            if (!arr) arr = [];
            if (groups) {
                for (var i in groups) {
                    if (gid > 0) {
                        if (groups[i].id == gid) {
                            arr.push(gid);
                            if (groups[i].subGroups) {
                                arr = this.findGroupAndSub(groups[i].subGroups, 0, arr);
                            }
                        } else {
                            if (groups[i].subGroups) {
                                arr = this.findGroupAndSub(groups[i].subGroups, gid, arr);
                            }
                        }
                    } else {
                        arr.push(groups[i].id);
                        if (groups[i].subGroups) {
                            arr = this.findGroupAndSub(groups[i].subGroups, 0, arr);
                        }
                    }
                }
            }

            return arr;
        },
        setRankPlayers(g) {
            if (!g || g <= 0) {
                this.rankPlayers = this.clone(this.players);
            } else {
                var garr = this.findGroupAndSub(this.actData.groups, g);
                var players = this.players.filter(x => garr.findIndex(z => z == x.groupId) >= 0);
                this.rankPlayers = players;
            }
            this.rankPlayers.sort((a, b) => {
                if (a.ticket == b.ticket) {
                    return a.serial - b.serial;
                } else {
                    return b.ticket - a.ticket;
                }
            });
            var cc = this.rankPlayers.length;
            for (var i = 0; i < cc; i++) {
                if (!this.rankPlayers[i].cover) {
                    this.rankPlayers[i].cover = '../image/deface.png';
                }
            }
        },
        changeAudioType(n) {
            this.musicType = n;
            this.$forceUpdate();
        },
        changeVideoType(n) {
            this.videoType = n;
            this.$forceUpdate();
        },
        updateInfo(n) {
            this.enrollObj.info = n;
        },
        // 上传图片微信
        uploadOneFile() {
            const that = this;
            wx.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    var locId = res.localIds[0];
                    wx.getLocalImgData({
                        localId: locId,
                        success(loc) {
                            var blob = that.dataURLtoBlob(loc.localData);
                            that.uploadFile(blob, 'image');
                        }
                    })
                }
            });
        },
        // 数据链接
        dataURLtoBlob(dataurl) {
            var aar, mime, bstr;
            if (dataurl.indexOf('data:image/') == 0) {
                arr = dataurl.split(',');
                mime = arr[0].match(/:(.*?);/)[1];
                bstr = atob(arr[1]);
            } else {
                bstr = atob(dataurl);
                mime = "image/jpg";
            }
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        requestOssToken(fs, fe, ...ps) {
            if (!this.ossToken) {
                const that = this;
                this.request({
                    url: 'common/oss/cert',
                    method: 'get',
                    success: function (res) {
                        if (res.code == 0) {
                            that.ossToken = res.data;
                            if (fs) fs(ps);
                        } else {
                            if (fe) fe(ps);
                        }
                    }, error: function (a, b) {
                        if (fe) fe(ps);
                    }
                });
            } else {
                if (fs) fs(ps);
            }
        },
        uploadFile(file, type) {
            const that = this;
            this.requestOssToken(function (ps) {
                that.uploadInner(ps[0], ps[1]);
            }, function (ps) {
                that.uploadFail(ps[1]);
            }, file, type);
        },
        // 上传失败
        uploadFail(type) {
            vant.Dialog.alert({ message: '文件上传失败' });
            if (type == 'image') {
                var len = this.photoList.length;
                this.photoList.splice(len - 1, 1);

            } else if (type == 'audio') {
                this.audioList = [];
                this.enrollObj.audio = '';
            } else if (type == 'video') {
                this.videoList = [];
                this.enrollObj.video = '';
            }
        },
        // 删除图片
        delPhoto(file) {
            if (file.key) {
                this.removeFile(file.key);
            }
            this.photoList = this.photoList.filter(x => x.url != file.url);
            var ary = [];
            this.photoList.forEach((val, idx, a) => {
                ary.push(val.key);
            });
            this.enrollObj.photo = JSON.stringify(ary);
        },
        // 获取远程地址
        getRemoteName(file, type) {
            if (!type) type = "image";
            var sub = file.name.substr(file.name.lastIndexOf('.'));
            var date = new Date();
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m > 9 ? m : '0' + m;
            var d = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
            var n = parseInt(Math.random() * 10000000);
            return type + '/' + y + m + d + '_' + n + sub;
        },
        uploadImgCheck(file) {
            const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
            const isLt1M = file.size / 1024 / 1024 < 3
            if (!isIMAGE) {
                vant.Toast('上传文件只能是图片格式!')
            }
            if (!isLt1M) {
                vant.Toast('上传文件大小不能超过 3MB!')
            }
            return isIMAGE && isLt1M
        },
        uploadAudioCheck(file) {
            var isMp3 = file.type == "audio/mpeg";
            var isLt30m = file.size / 1024 / 1024 <= 30;
            if (!isMp3) {
                vant.Toast('选手音频只支持MP3格式！');
            }
            if (!isLt30m) {
                vant.Toast('选手音频文件大小不能超过30MB！');
            }
            return isMp3 && isLt30m;
        },
        uploadVideoCheck(file) {
            var isMp4 = file.type == "video/mp4";
            var isLt50m = file.size / 1024 / 1024 <= 50;
            if (!isMp4) {
                vant.Toast('选手视频只支持MP4格式！');
            }
            if (!isLt50m) {
                vant.Toast('选手视频文件大小不能超过50MB');
            }
            return isMp4 && isLt50m;
        },
        getCos() {
            return new COS({
                SecretId: this.ossToken.secretId,
                SecretKey: this.ossToken.secretKey,
                SecurityToken: this.ossToken.token
            });
        },
        removeFile(key) {
            const that = this;
            this.requestOssToken(function (ps) {
                that.removeFileInner(ps[0]);
            }, function (ps) {

            }, key);
        },
        removeFileInner(key) {
            var cos = this.getCos();
            cos.deleteObject({
                Bucket: this.ossToken.bucket,
                Region: this.ossToken.region,
                Key: key,
            }, function (err, data) { });
        },
        uploadInner(file, type) {
            if (!type) type = "image";
            var cos = this.getCos();
            var key;
            if (file instanceof Blob) {
                var ext = ".jpg";
                if (file.type.toLowerCase().indexOf("png") > 0)
                    ext = ".png";

                key = this.getRemoteName({ name: 'aaa' + ext }, type);
            } else {
                key = this.getRemoteName(file, type);
            }
            const that = this;
            cos.uploadFile({
                Bucket: this.ossToken.bucket,
                Region: this.ossToken.region,
                Key: key,
                Body: file,
                SliceSize: 1024 * 1024 * 5, //分块上传文件
                onProgress(data) {
                    //上传进度
                },
                onFileFinish(err, data, opt) {
                    if (!err && data.statusCode == 200) {
                        //上传成功
                        var key = data.key ? data.key : null;
                        var loc = data.Location;
                        if (!key) {
                            var n = loc.indexOf('/', 8);
                            key = loc.substr(n + 1);
                        }
                        loc = 'https://' + loc;
                        var obj = { url: loc, key: key };
                        if (type == "image") {
                            that.photoList.push(obj);
                            var ary = [];
                            that.photoList.forEach((val, idx, aa) => {
                                ary.push(val.key);
                            });
                            that.enrollObj.photo = JSON.stringify(ary);
                        } else if (type == "audio") {
                            that.audioList = [{ url: loc, key: key }];
                            that.enrollObj.audio = key;
                        } else if (type == "video") {
                            that.videoList = [{ url: loc, key: key }];
                            that.enrollObj.video = key;
                        }
                    } else {
                        that.uploadFail(type);
                    }
                }
            }, function (err, data) {

            });
        },
        selGroupDone(e) {
            this.showPopGroup = false;
            this.showGroupLabel = e.selectedOptions.map((option) => option.name).join('/');
        },
        cancelSelect() {
            this.votePlayers = [];
            this.players.forEach(item => {
                item.select = false;
            });
            this.playerInfo.select = false;
            $(".multi_vote").hide();
            $("#app").css('padding-bottom', '');
        },
        selectDefaultGroup() {
            var that = this;
            if (that.pageIndex == 1) {
                that.curGroup = (!that.showAllGroup && that.actData.groups.length > 0) ? that.actData.groups[0] : null;
                that.loadGroupPlayer(that.curGroup);
            } else if (that.pageIndex == 3)
                that.loadGroupPlayer(null);
        }
    },
    watch: {
        pageIndex(newValue, oldValue) {
            window.scrollTo(0, 0);

            if (newValue == 1 || newValue == 3)
                this.selectDefaultGroup();
        }
    }
})
